from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet
from django.contrib.auth.hashers import make_password,check_password
from django.conf import settings


from .utils import send_message
from .models import *
from shops.models import ShopsModel
from .utils import MyJwt
from user.utils import MyAlipay
from .serializers import *
from shops.serializers import ShopsSer,GoodSer,GoodTypeSer

import os
import json
import random
import redis
import datetime


# 短信验证码
class SendCode(ViewSet):

    def smscode(self, request):
        mobile = request.data.get('mobile')

        sms_code = random.randint(1000, 9999)
        expire = 5

        result = send_message(sms_code, mobile, expire)

        r = redis.Redis(host='localhost', port=6379, db=0)
        sms_key = 'sms_%s' % mobile
        r.set(sms_key, sms_code)

        return Response({'code': 0, 'msg': '短信验证码发送成功，请注意查收'})


# 用户视图
class UserView(ViewSet):

    # 注册
    def register(self, request):

        nickname = request.data.get('nickname')
        mobile = request.data.get('mobile')
        password = request.data.get('password')
        code = request.data.get('code')

        if not [nickname, mobile, password, code]:
            return Response({'code': 2, 'msg': '用户信息不完整'})

        # 注册用户
        user = UserModel.objects.filter(nickname=nickname, is_delete=False).first()

        if user:
            return Response({'code': 1, 'msg': '用户已注册'})

        # 注册商家
        user = ShopsModel.objects.filter(nickname=nickname, is_delete=False).first()
        if user:
            return Response({'code': 1, 'msg': '用户已注册'})
        pwd = make_password(password, 'pbkdf2_sha256')
        UserModel.objects.create(nickname=nickname, password=pwd, mobile=mobile, role_id=1)  # 默认普通用户
        return Response({'code': 0, 'msg': '注册成功'})

    # 登录
    def login(self, request):
        try:
            nickname = request.data.get("nickname")
            mobile = request.data.get("mobile")
            password = request.data.get("password")

            # 占位符 判断登陆的是商家还是用户
            type = None
            user = ShopsModel.objects.filter(nickname=nickname, mobile=mobile, is_delete=False).first()
            if user:
                if user.is_apply == False:
                    return Response({"code": 400, "msg": "审核中！请耐心等待！"})
                type = 2

            if not type:
                user = UserModel.objects.filter(nickname=nickname, mobile=mobile, is_delete=False).first()
                if not user:
                    return Response({"code": 400, "msg": "用户不存在！"})

            if check_password(password, user.password):
                user.last_login = datetime.datetime.now()  # 更新登录时间
                user.save()
                # 有权限登录站点

                myjwt = MyJwt()

                if type == 2:
                    ser = ShopsSer(user)
                else:
                    ser = UserSer(user)
                return Response({
                    "code": 200,
                    "msg": "登录成功！",
                    "token": myjwt.encode({'id': user.id, "nickname": user.nickname}),
                    "data": ser.data,
                    "user_type": type,
                })
            return Response({"code": 1, "msg": "用户名或密码错误！"})
        except Exception as e:
            print("错误", e)

    # 获取用户信息
    def userinfo(self, request):

        user_id = request.query_params.get('user_id')
        # user_id = request.data.get("user_id")
        type = request.data.get('type')
        print(user_id)
        try:
            user = UserModel.objects.filter(id=user_id, is_delete=False)
            if not user:
                return Response({"code": 400, "msg": "用户不存在！"})

            if type != None:
                return Response({"code": 500, "msg": "非法请求！"})

            ser = UserSer(user, many=True)
            return Response({"code": 200, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("错误", e)
            return Response({"code": 400, "msg": "获取失败"})

    # 修改用户信息
    def update_info(self, request):

        user_id = request.data.get('user_id')

        nickname = request.data.get('nickname')
        avatar_url = request.data.get('avatar')
        mobile = request.data.get('mobile')
        password = request.data.get('password')

        try:
            flag = UserModel.objects.filter(nickname=nickname, is_delete=False).exclude(id=user_id).count()

            if flag != 0:
                return Response({'code': 400, 'msg': '用户数据重复'})

            user = UserModel.objects.filter(id=user_id, is_delete=False)

            if not user:
                return Response({'code': 400, 'msg': '用户不存在'})

            if nickname:
                user.update(nickname=nickname)
            if avatar_url:
                user.update(avatar_url=avatar_url)
            if mobile:
                user.update(mobile=mobile)
            if password:
                hash_pwd = make_password(password, 'pbkdf2_sha256')
                user.update(password=hash_pwd)
            return Response({'code': 200, 'msg': '修改成功'})
        except Exception as e:
            print(str(e))
            pass


# 获取菜品分类
class GoodTypeView(ViewSet):
    # 获取
    def list(self, request, pk):
        try:
            goods_type = ShopsModel.objects.get(id=pk)
            print(goods_type)
            goods = goods_type.goodtypemodel_set.filter(is_delete=False).all()
            ser = GoodTypeSer(goods, many=True)
            return Response({"code": 200, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("错误", e)
            return Response({"code": 400, "msg": "获取失败"})


# 获取菜品详情
class GoodsView(ViewSet):
    def good_get(self, request, pk):
        try:
            g1 = GoodTypeModel.objects.get(id=pk)

            good = g1.goodsmodel_set.filter(is_delete=False).all()

            goods_ser = GoodSer(good, many=True)

            return Response({"code": 200, "data": goods_ser.data})
        except Exception as e:
            print("错误", e)
            return Response({"code": 400, "msg": "获取失败"})


# 地址管理
class AddressView(ViewSet):

    # 获取用户地址
    def addressList(self, request):
        try:
            user_id = request.query_params.get("user_id")
            print(user_id)
            addr = AddressModel.objects.filter(user_id=int(user_id), is_delete=False).all()
            print(addr)
            ser = AddressSer(addr, many=True)
            return Response({"code": 200, "msg": "获取地址成功", "data": ser.data})
        except Exception as e:
            print("获取失败的原因", e)
            return Response({"code": 400, "msg": "获取地址失败"})

    # 添加地址
    def add(self, request):
        try:
            id = request.data.get("user_id")
            nickname = request.data.get("nickname")
            mobile = request.data.get("mobile")
            address = request.data.get("address")
            is_default = request.data.get("is_default")
            print(id, nickname, mobile, address, is_default)
            if is_default == "true":
                AddressModel.objects.filter(user_id=id, is_delete=False).update(is_default=False)

            address_data = {
                "user": id,
                "nickname": nickname,
                "mobile": mobile,
                "address": address,
                "is_default": is_default,
            }
            serializer = AddressSer(data=address_data)
            serializer.is_valid(raise_exception=True)
            serializer.save()

            return Response({"code": 200, "msg": "添加地址成功"})
        except Exception as e:
            print("添加失败的原因", e)
            return Response({"code": 400, "msg": "添加地址失败"})

    # 修改地址
    def update(self, request):
        try:
            user_id = request.data.get('id')

            id = request.data.get("add_id")
            nickname = request.data.get("nickname")
            mobile = request.data.get("mobile")
            address = request.data.get("address")
            is_default = request.data.get("is_default")

            address_dict = AddressModel.objects.filter(id=id, user_id=user_id, is_delete=False).first()
            if not address_dict:
                return Response({"code": 400, "msg": "地址不存在！"})

            if is_default == "true":
                AddressModel.objects.filter(user_id=user_id, is_delete=False).update(is_default=False)

            data = {
                "id": id,
                "user": user_id,
                "nickname": nickname,
                "mobile": mobile,
                "address": address,
                "is_default": is_default,
            }
            ser = AddressSer(instance=address_dict, data=data)
            ser.is_valid(raise_exception=True)
            ser.save()

            return Response({"code": 200, "msg": "修改成功！"})
        except Exception as e:
            print("错误", e)
            pass

    # 删除地址
    def delete(self, request, pk):
        try:

            user_id = request.data.get("id")
            addr = AddressModel.objects.filter(id=pk, user_id=user_id, is_delete=False)

            if not addr:
                return Response({"code": 400, "msg": "地址不存在"})

            addr.update(is_delete=True)
            return Response({"code": 200, "msg": "删除成功"})

        except Exception as e:
            print("错误", e)
            pass


# 购物车
class ShoppingView(ViewSet):

    # 添加购物车
    def shoppinglist(self, request):

        user_id = request.data.get("user_id")
        shops_id = request.data.get("shops_id")
        goods_id = request.data.get("goods_id")
        num = request.data.get("num")

        try:
            UserShoppingModel.objects.create(user_id=user_id, shops_id=shops_id, goods_id=goods_id, num=num)
            return Response({"code": 200, "msg": "添加购物车成功"})
        except Exception as e:
            print('失败的原因',e)
            return Response({"code": 400, "msg": "添加购物车失败"})

    # 获取购物车
    def shopping_get(self, request):
        try:
            shopping = UserShoppingModel.objects.all()
        except Exception as e:
            print(e)
            return Response({"code": 400, "msg": "获取失败"})

        shoppings = UserShoppingSer(shopping, many=True)
        return Response({
            "code": 200,
            "msg": "获取成功",
            "data": shoppings.data
        })

    # 删除购物车
    def shopping_del(self, request):
        pass


# 上传图片
class UpyouImgView(ViewSet):

    def post(self, request):

        file = request.data.get("file")

        id = request.data.get("id")

        filepath = os.path.join(settings.STATICFILES_DIRS[0])

        filename = filepath + file.name

        with open(filename, "wb") as f:
            f.write(file.file.read())

        print("file.name:", file.name)
        user = ShopsModel.objects.get(id=id)
        user.image = file.name
        user.save()

        return Response({
            'code': '200',
            'msg': '上传成功',
            'avatar': file.name
        })


# 收藏管理
class CollectView(ViewSet):

    # 添加收藏
    def collect_post(self, request):
        try:
            user_id = request.data.get("user_id")
            shops_id = request.data.get("id")
            print(user_id, shops_id)
            collect = CollectModel.objects.filter(user_id=user_id, shops_id=shops_id, is_delete=False).first()

            if collect:
                return Response({"code": 400, "msg": "此店铺已收藏"})

            CollectModel.objects.create(user_id=user_id, shops_id=shops_id)

            return Response({"code": 200, "msg": "收藏成功"})

        except Exception as e:
            print("收藏失败的原因", e)
            return Response({"code": 400, "msg": "收藏失败"})

    # 获取收藏
    def collect_get(self, request):
        try:
            collect = CollectModel.objects.filter(is_delete=False)
            collect_list = CollectSer(collect, many=True)
            return Response({"code": 200, "msg": "获取成功", "data": collect_list.data})
        except Exception as e:
            print(e)
            return Response({"code": 400, "msg": "获取失败"})

    # 取消收藏
    def collect_del(self, request, pk):
        try:
            # user_id = request.data.get("user_id")
            user_id = request.query_params.get("user_id")
            collect = CollectModel.objects.filter(id=pk, user_id=user_id, is_delete=False)
            collect.update(is_delete=True)

            return Response({"code": 200, "msg": "取消收藏成功"})
        except Exception as e:
            print("取消收藏失败", e)
            return Response({"code": 400, "msg": "取消收藏失败"})


# 优惠券  待完成
class CouponsView(ViewSet):
    
    pass


# 用户领取优惠券

# 评论
class CommentView(ViewSet):

    # 添加评论
    def Comment_post(self, request):
        user_id = request.data.get("user_id")
        shops_id = request.data.get("shops_id")
        order_id = request.data.get("order_id")
        content = request.data.get("content")

        try:
            CommentModel.objects.create(user_id=user_id, shops_id=shops_id, order_id=order_id, content=content)
            return Response({"code": 200, "msg": "评论成功"})
        except Exception as e:
            print("失败的原因", e)
            return Response({"code": 400, "msg": "评论失败"})

    # 获取评论
    def comment_list(self, request, pk):
        try:
            comment = CommentModel.objects.filter(shops_id=pk, is_delete=False).all()

            comment_list = CommentSer(comment, many=True)

            return Response({
                "code": 200,
                "msg": "获取商家评论成功",
                "data": comment_list.data
            })
        except Exception as e:
            print("获取失败", e)
            return Response({"code": 400, "msg": "获取商家评论失败"})


# 订单
class OrderView(ViewSet):
    myalipay = MyAlipay()

    # 创建订单
    def order_post(self, request):
        try:
            # user_id = request.query_params.get("user_id")
            user_id = request.data.get("user_id")
            goods_id = request.data.get("goods_id")
            shops_id = request.data.get("shops_id")
            pay_method = request.data.get("pay_method")
            total_count = request.data.get("total_count")
            total_amount = request.data.get("total_amount")
            address_id = request.data.get("address_id")
            coupons_id = request.data.get("coupons_id")

            print(user_id, goods_id, shops_id, pay_method, total_count, total_amount, address_id, coupons_id)
            # shops = int(shops_id)
            goods = json.loads(goods_id)
            if not goods:
                return Response({"code": 204, "message": "请先选择商品！"})

            rder_id = datetime.datetime.now().timestamp()
            # 订单编号
            order_id = str(rder_id * 1000000) + str(user_id) + str(random.randint(100000, 999999))

            order = OrderModel.objects.create(user_id=user_id,  pay_method=pay_method, total_amount=total_amount,order_id=order_id,
                    total_count=total_count, address_id=address_id, goods_id=goods_id, shops_id=shops_id, coupons_id=coupons_id)

            for i in goods:
                OrderGoods.objects.create(order_id=order.id, goods_id=i["id"], sum=i["sum"],sum_price=i["sum_price"])

            print('------------', order)

            url = self.myalipay.get_pay_url(order_id, total_amount)
            return Response({"code": 200, "msg": "创建成功", "url": url})

        except Exception as e:
            print("创建失败的原因", e)
            return Response({"code": 400, "msg": "创建失败"})

    # 判断订单是否支付成功
    def check_order(self, request):
        try:
            order_id = request.data.get("out_trade_no")

            # order_id = request.query_params.get("out_trade_no")

            order = OrderModel.objects.filter(order_id=order_id, is_delete=False)

            if not order:
                return Response({"code": 400, "msg": "没有此订单"})

            if not self.myalipay.check(order_id):
                return Response({"code": 400, "msg": "支付失败"})

            order.update(pay_state=1)
            return Response({"code": 200, "msg": "支付成功"})

        except Exception as e:
            print("判断支付的结果为", e)
            pass

    # 获取用户所有订单
    def order_get(self, request):
        try:
            user_id = request.query_params.get("user_id")
            # user_id = request.data.get("user_id")
            order = OrderModel.objects.filter(user_id=user_id, is_delete=False).all()
            order_ser = OrderSer(order, many=True)

            return Response({"code": 200, "msg": "获取成功", "data": order_ser.data})
        except Exception as e:
            print("获取失败的原因", e)
            return Response({"code": 400, "msg": "获取失败"})

    # 获取用户没有支付的订单
    def order_list(self, request):
        try:
            user_id = request.query_params.get("user_id")
            # user_id = request.data.get("user_id")
            order = OrderModel.objects.filter(user_id=user_id, pay_state=0, is_delete=False).all()
            order_ser = OrderSer(order, many=True)

            return Response({"code": 200, "msg": "获取成功", "data": order_ser.data})
        except Exception as e:
            print("获取失败的原因", e)
            return Response({"code": 400, "msg": "获取失败"})

    # 获取用户支付的订单
    def order_pay(self, request):
        try:
            user_id = request.query_params.get("user_id")
            # user_id = request.data.get("user_id")
            order = OrderModel.objects.filter(user_id=user_id, pay_state=1, is_delete=False).all()
            order_ser = OrderSer(order, many=True)

            return Response({"code": 200, "msg": "获取成功", "data": order_ser.data})
        except Exception as e:
            print("获取失败的原因", e)
            return Response({"code": 400, "msg": "获取失败"})

    # 获取没有支付的订单的地址
    def not_order_get(self, request, pk):
        try:
            order = OrderModel.objects.filter(id=pk, pay_method=1, pay_state=0, is_delete=False).first()
            print('--------',order)
            pay_url = self.myalipay.get_pay_url(order.order_id, str(order.total_amount))
            print('-======', pay_url)
            return Response({"code": 200, 'msg': '正在跳转支付地址', 'pay_url': pay_url})

        except Exception as e:
            print("获取没有支付的订单失败", e)
            return Response({"code": 500, 'msg': "跳转失败"})

    # 取消支付订单
    def not_order_del(self, request, pk):
        try:
            # user_id = request.data.get("user_id")
            user_id = request.query_params.get("user_id")
            print(user_id)
            order = OrderModel.objects.filter(id=pk, user_id=user_id, pay_method=1, pay_state=0, is_delete=False)
            print('order', order)
            order.first().ordergoods_set.update(is_delete=True)
            print("------", order,type(order))
            order.update(is_delete=True)

            return Response({"code": 200, "msg": "取消支付成功"})
        except Exception as e:
            print("取消失败", e)
            return Response({"code": 400, "msg": "取消支付失败"})

    # 获取订单的详情
    def order_get_details(self, request, pk):
        try:
            # user_id = request.query_params.get("user_id")
            user_id = request.data.get("user_id")
            print(user_id)

            order = OrderModel.objects.filter(id=pk, user_id=user_id, is_delete=False).first()

            order_list = order.ordergoods_set.all()
            print('order_list', order_list)

            list = []
            for i in order_list:
                goods = i.goods
                list.append(goods)
                
            order_ser = OrderSer(order)
            return Response({"code": 200, "msg": "获取订单详情成功", "data": order_ser.data})

        except Exception as e:
            print("获取详情失败的原因:", e)
            return Response({"code": 400, "msg": "获取详情失败"})

    # 删除订单
    def order_del(self, request, pk):
        try:
            # user_id = request.data.get("user_id")
            user_id = request.query_params.get("user_id")
            print(user_id)
            order = OrderModel.objects.filter(id=pk, user_id=user_id, is_delete=False)
            print('order', order)
            order.first().ordergoods_set.update(is_delete=True)
            print("------", order, type(order))
            order.update(is_delete=True)

            return Response({"code": 200, "msg": "删除订单成功"})
        except Exception as e:
            print("删除订单失败", e)
            return Response({"code": 400, "msg": "删除订单失败"})

# 沟通





